<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>通过鼠标控制绘制</title>
    <script src="test.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        margin: 50px auto 0;
        display: block;
        background: yellow;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="400px" height="400px" style="background-color: blue"></canvas>

    <script>
      // 1获取webgl
      const canvas = document.getElementById('canvas')
      const gl = canvas.getContext('webgl')
      // 2.初始化webgl
      // 3.定义顶点着色器和片元着色器
      const vsSource = `
       attribute vec4 aPosition;
      void main(){
      gl_Position=aPosition;
       gl_PointSize=20.0;
      }`
      const fsSource = `void main(){
       gl_FragColor = vec4(1.0,0.0,0.0,1.0);
      }`
      // 4. 使用着色器程序
      const program = initShader(gl, vsSource, fsSource)
      gl.useProgram(program)
      // 5.获取aPosition的值
      const aPosition = gl.getAttribLocation(program, 'aPosition')
      // const points = []
      gl.vertexAttrib1f(aPosition, 0.0)
      gl.drawArrays(gl.POINTS, 0, 1) //重新绘制
      // 6.把屏幕坐标转化成webgl坐标
      canvas.onmousemove = function (ev) {
        const x = ev.clientX
        const y = ev.clientY
        const rect = ev.target.getBoundingClientRect()
        const domx = x - rect.x
        const domy = y - rect.y
        console.log('canvas原点坐标', domx, domy)
        width = canvas.width
        height = canvas.height
        const widthX = width / 2
        const heightY = height / 2
        console.log('webgl原点坐标', domx, domy)
        // canvas原点坐标转webgl原点坐标
        const clickX = (domx - widthX) / widthX
        const clickY = (heightY - domy) / heightY
        console.log('webgl原点坐标', clickX, clickY)
        gl.vertexAttrib2f(aPosition, clickX, clickY)
        gl.drawArrays(gl.POINTS, 0, 1)
        // points.push({ clickX, clickY })
        // for (let i = 0; i < points.length; i++) {
        //   gl.vertexAttrib2f(aPosition, points[i].clickX, points[i].clickY)
        //   gl.drawArrays(gl.POINTS, 0, 1)
        // }
      }
    </script>
  </body>
</html>
